<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>问卷统计 - {{ questionnaireTitle }}</span>
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="statsData">
        <!-- 基础统计信息 -->
        <el-row :gutter="20" class="stats-overview">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-number">{{ statsData.totalSubmissions }}</div>
              <div class="stats-label">总答卷数</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-number">{{ statsData.totalQuestions }}</div>
              <div class="stats-label">题目数量</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-number">{{ statsData.completionRate }}%</div>
              <div class="stats-label">完成率</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-number">{{ statsData.avgTime }}分钟</div>
              <div class="stats-label">平均用时</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 题目统计 -->
        <div class="question-stats">
          <h3>题目统计</h3>
          <div v-for="(question, index) in statsData.questions" :key="question.id" class="question-stat-item">
            <div class="question-header">
              <h4>{{ index + 1 }}. {{ question.content }}</h4>
              <span class="question-type">{{ getQuestionTypeText(question.questionType) }}</span>
            </div>
            
            <!-- 选择题统计 -->
            <div v-if="question.questionType !== 'text'" class="options-stats">
              <div v-for="option in question.options" :key="option.id" class="option-stat">
                <div class="option-info">
                  <span class="option-label">{{ option.optionLabel }}</span>
                  <span class="option-count">{{ option.count }}人 ({{ getPercent(option.count, question.total) }}%)</span>
                </div>
                <el-progress 
                  :percentage="getPercent(option.count, question.total)" 
                  :color="getProgressColor(index)"
                  :stroke-width="8"
                />
              </div>
            </div>
            
            <!-- 文本题统计 -->
            <div v-else class="text-stats">
              <div class="text-answers">
                <div v-for="(answer, idx) in question.answers" :key="idx" class="text-answer">
                  <el-tag size="small" type="info">{{ idx + 1 }}</el-tag>
                  <span class="answer-text">{{ answer }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 时间趋势图 -->
        <div class="trend-chart" v-if="statsData.trendData">
          <h3>答卷趋势</h3>
          <div ref="trendChart" style="height: 300px;"></div>
        </div>
      </div>
      
      <div v-else class="empty-container">
        <el-empty description="暂无统计数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup name="QnQuestionnaireStats">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getQuestionnaireStats, getQuestionnaire } from '@/api/questionnaire'
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const questionnaireTitle = ref('')
const statsData = ref(null)
const trendChart = ref(null)

// 获取问卷统计
async function loadStats() {
  const id = route.params.id
  try {
    const [statsRes, detailRes] = await Promise.all([
      getQuestionnaireStats(id),
      getQuestionnaire(id)
    ])
    statsData.value = statsRes.data
    questionnaireTitle.value = detailRes.data.title
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取题目类型文本
function getQuestionTypeText(type) {
  const typeMap = {
    'single': '单选题',
    'multiple': '多选题',
    'text': '填空题',
    'rating': '评分题'
  }
  return typeMap[type] || '未知类型'
}

// 计算百分比
function getPercent(count, total) {
  if (!total) return 0
  return Math.round((count / total) * 100)
}

// 获取进度条颜色
function getProgressColor(index) {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  return colors[index % colors.length]
}

// 初始化趋势图
function initTrendChart() {
  if (!statsData.value?.trendData || !trendChart.value) return
  
  const chart = echarts.init(trendChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: statsData.value.trendData.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: statsData.value.trendData.counts,
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }
  chart.setOption(option)
}

// 返回上一页
function goBack() {
  router.back()
}

onMounted(async () => {
  await loadStats()
  await nextTick()
  initTrendChart()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px;
}

.stats-overview {
  margin-bottom: 30px;
}

.stats-card {
  text-align: center;
  padding: 20px;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.question-stats {
  margin-top: 30px;
}

.question-stats h3 {
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.question-stat-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-header h4 {
  margin: 0;
  color: #303133;
  flex: 1;
}

.question-type {
  background: #409EFF;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.options-stats {
  margin-left: 20px;
}

.option-stat {
  margin-bottom: 15px;
}

.option-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.option-label {
  font-weight: 500;
  color: #606266;
}

.option-count {
  color: #909399;
  font-size: 12px;
}

.text-stats {
  margin-left: 20px;
}

.text-answers {
  max-height: 200px;
  overflow-y: auto;
}

.text-answer {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.answer-text {
  margin-left: 8px;
  flex: 1;
  word-break: break-all;
}

.trend-chart {
  margin-top: 30px;
}

.trend-chart h3 {
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.empty-container {
  padding: 40px;
  text-align: center;
}
</style> 